#include "napi/native_api.h"
#include <js_native_api_types.h>

#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>

#define NAPI_CALL(env, call)                          \
  do {                                                \
    napi_status status = (call);                      \
    if (status != napi_ok) {                          \
      napi_throw_error((env), NULL, #call " failed"); \
      return NULL;                                    \
    }                                                 \
  } while (0)

// sync
static napi_value Add(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};
    NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args , nullptr, nullptr));

    napi_valuetype valuetype0;
    NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0));

    napi_valuetype valuetype1;
    NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1));

    double value0;
    NAPI_CALL(env, napi_get_value_double(env, args[0], &value0));

    double value1;
    NAPI_CALL(env, napi_get_value_double(env, args[1], &value1));

    napi_value sum;
    NAPI_CALL(env, napi_create_double(env, value0 + value1, &sum));

    return sum;

}
static napi_value Tid(napi_env env, napi_callback_info info)
{
    napi_value tid;
    sleep(3);
    napi_create_uint32(env, pthread_self(), &tid);

    return tid;

}
// async
struct HelloData {
    napi_async_work work;
    napi_deferred deferred;
    double inData;
};

static void AsyncFunc(napi_env env, void* data) {
    HelloData *helloData = (HelloData *)data;
    sleep(5);
    helloData->inData = pthread_self();
}

static void AsyncFuncComplete(napi_env env, napi_status status, void* data) {
    HelloData *helloData = (HelloData *)data;
    napi_value obj;
    napi_value name;
    napi_value tid;
    if (helloData->inData <= 10) {
        napi_create_string_utf8(env,
                "napi_resolve_deferred",
                NAPI_AUTO_LENGTH,
                &name);
        unsigned long int tmp = helloData->inData;
        napi_create_uint32(env, tmp, &tid);
        napi_create_object(env, &obj);
        napi_set_named_property(env, obj, "name", name);
        napi_set_named_property(env, obj, "tid", tid);

        napi_resolve_deferred(env, helloData->deferred, obj);
    } else {
        //        napi_create_string_utf8(env,
        //                "napi_reject_deferred",
        //                NAPI_AUTO_LENGTH,
        //                &tmp);
        unsigned long int tmp = helloData->inData;
        napi_create_uint32(env, tmp, &tid);
        napi_reject_deferred(env, helloData->deferred, tid);
    }
    napi_delete_async_work(env, helloData->work);
    free(data);
}

static napi_value CPUWork(napi_env env, napi_callback_info info) {
    napi_value work_name, promise;
    napi_status status;
    size_t argc = 1;
    napi_value args[1];
    status = napi_get_cb_info(env, info, &argc, args, NULL, NULL);
    if (argc < 1) {
        napi_throw_type_error(env, NULL, "Wrong number of arguments");
        return NULL;
    }

    napi_valuetype valuetype;
    status = napi_typeof(env, args[0], &valuetype);
    if (valuetype != napi_number) {
        napi_throw_type_error(env, NULL, "Wrong arguments");
        return NULL;
    }
//    return args[0];
    double value;
    status = napi_get_value_double(env, args[0], &value);

    HelloData* helloData = (HelloData*)malloc(sizeof(HelloData));
    helloData->work = NULL;
    helloData->inData = value;
    napi_create_promise(env, &(helloData->deferred), &promise);
    napi_create_string_utf8(env,
                            "Async Work",
                            NAPI_AUTO_LENGTH,
                            &work_name);
    napi_create_async_work(env,
                            NULL,
                            work_name,
                            AsyncFunc,
                            AsyncFuncComplete,
                            helloData,
                            &(helloData->work));
    napi_queue_async_work(env, helloData->work);

    return promise;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        { "add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "CPUWork", nullptr, CPUWork, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "Tid", nullptr, Tid, nullptr, nullptr, nullptr, napi_default, nullptr }
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version =1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "libhello",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterModule(void)
{
    napi_module_register(&demoModule);
}
